# -*- coding:utf-8 -*-
# Author:凌逆战 | Never
# Date: 
"""
Analysis, synthesis
hann只需要分析的时候乘一次，sqrthann分析和合成都要乘
"""
import scipy.signal as signal
import librosa
import numpy as np
import matplotlib.pyplot as plt

window_len = 512
frame_len = 256
hann = signal.windows.hann(window_len, sym=False)
sqrthann = np.sqrt(hann)


def Analysis(wav, window_size, hop_size):
    """
    分帧加窗+fft
    Returns:
    """
    wav = wav[:-(len(wav) % hop_size)]  # 32768
    analyze_list = []

    max_i = len(wav) - window_size + 1
    for i in range(0, max_i, hop_size):
        win_array = wav[i: i + window_size] * sqrthann
        analyze_list.append(win_array)

    analyze_array = np.array(analyze_list)
    return analyze_array


def Synthesis(analyze_array, hop_size):
    """
    ifft+overlap_add
    Returns:
    """
    frame_num, window_size = analyze_array.shape
    wav_len = frame_num * hop_size + window_size - hop_size
    wav_sys = np.zeros((wav_len,), dtype=analyze_array.dtype)

    for index in range(frame_num):
        # analyze_array[frame_index] = np.fft.fft(analyze_array[frame_index], n=window_len)
        ytmp = analyze_array[index, :] * sqrthann
        wav_sys[index * hop_size: index * hop_size + window_len] += ytmp
        plt.figure()
        plt.plot(wav_sys[window_len - hop_size: -(window_len - hop_size)])
        plt.grid()
        plt.show()

    wav_sys = wav_sys[(window_size - hop_size): -(window_size - hop_size)]
    print("wav_sys.shape", wav_sys.shape)
    return wav_sys


wav = np.ones(shape=(32825,))
print("wav.shape", wav.shape)

analyze_array = Analysis(wav, window_len, frame_len)
print("analyze_array.shape", analyze_array.shape)
wav_sys = Synthesis(analyze_array, frame_len)
